import { assign, cloneDeep, omit } from 'lodash-es';
import { compile } from 'path-to-regexp';
import * as store from './store';

const toPath = compile('data-config/user/:userId');
const getUser = async () => await Manycore.User.getUserAsync();

interface IDataConfigEditable {
  categorys: string[];
  excludeModelNames: string[];
}
interface IDataConfig extends IDataConfigEditable {}

export const defaultDataConfig: IDataConfig = {
  categorys: [],
  excludeModelNames: [],
};

function getFullConfig(config?: Partial<IDataConfigEditable>): IDataConfig {
  return assign(cloneDeep(defaultDataConfig), omit(config, 'key'));
}

export async function getDataConfig() {
  const { userId } = await getUser();
  const path = toPath({ userId });
  const config = await store.getItem<IDataConfigEditable>({ key: path });
  return getFullConfig(config);
}

export async function updateDataConfig(config: IDataConfigEditable) {
  const { userId } = await getUser();
  store.setItem({
    key: toPath({ userId }),
    value: config,
  });
}
